<template>
  <div>
    <Card dis-hover>
      <Row style="margin-bottom: 10px;">
        <Col span="24" style="text-align: right;">
          <Button @click="prevStep" type="success" style="margin-right: 10px;" :disabled="current===0">
            <Icon type="ios-arrow-back"></Icon>
            上一步
          </Button>
          <Button @click="nextStep(current)" type="success" style="margin-right: 10px;" :disabled="current===1">
            下一步
            <Icon type="ios-arrow-forward"></Icon>
          </Button>
          <Button @click="checkOrSubmit" icon="md-play" type="primary" style="margin-right: 10px;"
                  :disabled="current!==1||(current===1 && $route.params.id!=0) || !hasPermission('Pages.FlowInstances.Launch')">
            启动
          </Button>
          <Button @click="restart" icon="md-refresh" type="info" style="margin-right: 10px;"
                  :disabled="current!==1 ||(current===1 && $route.params.id==0) || !hasPermission('Pages.FlowInstances.Restart') ">
            重启
          </Button>
          <Button @click="working" icon="md-time" type="warning"
                  :disabled="current!==1 || (current===1 && $route.params.id!=0) ||  !hasPermission('Pages.FlowInstances.Working')">
            暂存
          </Button>
        </Col>
      </Row>
      <Steps :current="current" style="margin-top:20px;margin-bottom:20px;">
        <Step title="基本信息"></Step>
        <Step title="填写表单"></Step>
      </Steps>
      <Card dis-hover v-show="current===0" style="height: calc(100vh - 272px);">
        <Form ref="instanceForm" :model="instance" label-position="top" :rules="instanceRule">
          <FormItem label="流程模板" prop="flowSchemeName">
            <Input ref="flowSchemeName" v-model="instance.flowSchemeName" readonly clearable placeholder=""
                   @on-focus="schemeFocus" @on-clear="flowSchemeClear" :disabled="$route.params.which===4">
            </Input>
          </FormItem>
          <FormItem label="流程名称" prop="name">
            <Input v-model="instance.name" clearable placeholder=""></Input>
          </FormItem>
          <FormItem label="流程描述" prop="description">
            <Input v-model="instance.description" type="textarea" :rows="4" clearable placeholder=""></Input>
          </FormItem>
        </Form>
      </Card>
      <Card dis-hover v-show="current===1" style="height: calc(100vh - 272px);">
       <form-build ref="form0" :form-template="JSON.parse(formScheme.schemeContent)" :models="data" :disabled="false"
                    :render-preview="false"
                    v-if="formScheme.formType===0"></form-build>

        <component ref="form1" :is="formScheme.schemeContent" v-if="formScheme.formType===1"
                   :disabled="false" :data="data"></component>
      </Card>

    </Card>
    <flow-scheme-select-modal v-if="flowSchemeSelectModalMount" v-model="flowSchemeSelectModalShow"
                              :modal-data="flowSchemeSelectModalData"
                              @on-submit="obtainSchemes"></flow-scheme-select-modal>
    <allot-modal :type="type" v-if="allotModalMount" v-model="allotModalShow" :modal-data="allotModalData"
                 @on-submit="allotSubmit"></allot-modal>
  </div>
</template>

<script lang="ts">
import {Component, Vue, Prop, Watch, Emit} from 'vue-property-decorator';
import AbpBase from '@/lib/abpbase';
import Util from '@/lib/util';
import FlowSchemeSelectModal from '@/components/common-modal/flow-scheme-select-modal.vue';
import FlowInstance from '@/store/entities/flow/flow-instance/flow-instance';
import FlowSchemeModal from '@/components/common-modal/flow-scheme-modal.vue';
import Runtime from '@/views/flow/flow-instance/module/runtime';
import AllotModal from '@/views/flow/flow-instance/modal/allot-modal.vue';
import FlowAreaViewOnly from '@/components/flow/flow-area-view-only.vue';

@Component({
  components: {AllotModal, FlowSchemeModal, FlowSchemeSelectModal, FlowAreaViewOnly},
})
export default class FlowInstanceInsert extends AbpBase {
  name: string = 'FlowInstanceInsert';

  data: any = {};
  drawer1: boolean = false;
  type: string;
  current: number = 0;
  flowSchemeSelectModalMount: boolean = false;
  flowSchemeSelectModalShow: boolean = false;
  flowSchemeSelectModalData: any = {};

  allotModalMount: boolean = false;
  allotModalShow: boolean = false;
  allotModalData: any = {};

  selectedSchemes: any[] = [];
  instance: FlowInstance = new FlowInstance();
  instanceRule = {
    flowSchemeName: [
      {
        validator: (rule, value, callback) => {
          if (!(this.$refs.flowSchemeName as any).value) {
            callback(new Error('流程模板是必须的'));
          } else {
            callback();
          }
        },
        trigger: 'blur,change',
        required: true,
      },
    ],
    name: [
      {
        required: true,
        message: '流程名称是必须的',
        trigger: 'blur,change',
      },
    ],
  };


  get formScheme() {
    return this.$store.state.formScheme.formScheme;
  }

  flowSchemeClear() {
    this.selectedSchemes = [];
    this.$forceUpdate();
  }


  async checkOrSubmit() {
    this.type = 'insert';
    let state: boolean = false;
    if (this.formScheme.formType === 0) {
      await (this.$refs.form0 as any).validator().then(async valid => {
        if (valid) {
          await (this.$refs.form0 as any).getData().then(data => {
            this.instance.formData = JSON.stringify(data);
            state = true;
          }).catch(error => {
          });
        }
      });
    }
    if (this.formScheme.formType === 1) {
      ((this.$refs.form1 as any).$refs.form as any).validate(valid => {
        if (valid) {
          this.instance.formData = JSON.stringify((this.$refs.form1 as any).getData());
          state = true;
        }
      });
    }
    if (state) {
      const runtime: Runtime = new Runtime(this.instance);
      if (runtime.nextNode.type === 'task' && (runtime.nextNode.info.allot === 'RUNNINGUSER' || runtime.nextNode.info.allot === 'RUNNINGROLE')) {
        this.allotModalData = {
          instance: this.instance,
          info: runtime.nextNode.info,
          creator: this.$store.state.session.user.id
        };
        this.allotModalMount = true;
        this.$nextTick(() => {
          this.allotModalShow = true;
        });
      } else {
        await this.$store.dispatch({
          type: 'flowInstance/createOrUpdateFlowInstance',
          data: {
            flowInstance: this.instance,
          },
        });
        this.$Message.success({
          background: true,
          content: '流程 ' + this.instance.name + ' 已启动',
          duration: this.$config.duration,
        });
        Util.closePage(this, 'flow-instance-insert');
        this.$router.push({name: 'launch'});
      }
    }
  }

  async working() {
    if (this.formScheme.formType === 0) {
      await (this.$refs.form0 as any).getData().then(data => {
        this.instance.formData = JSON.stringify(data);
      }).catch(error => {
      });
    }
    if (this.formScheme.formType === 1) {
      this.instance.formData = JSON.stringify((this.$refs.form1 as any).getData());
    }
    await this.$store.dispatch({
      type: 'flowInstance/workingFlowInstance',
      data: {
        flowInstance: this.instance,
      }
    });
    this.$Message.success({
      background: true,
      content: '流程 ' + this.instance.name + ' 已暂存',
      duration: this.$config.duration,
    });
    Util.closePage(this, 'flow-instance-insert');
    this.$router.push({name: 'draft'});
  }

  schemeFocus() {
    this.flowSchemeSelectModalData = {selectedSchemes: this.selectedSchemes};
    this.flowSchemeSelectModalMount = true;
    this.$nextTick(() => {
      this.flowSchemeSelectModalShow = true;
    });
  }

  obtainSchemes(selectedSchemes) {
    this.selectedSchemes = selectedSchemes;
    this.instance.flowSchemeName = selectedSchemes[0].schemeName;
    this.instance.flowSchemeId = selectedSchemes[0].id;
    this.instance.flowSchemeContent = selectedSchemes[0].schemeContent;
    this.$nextTick(async () => {
      await this.$store.dispatch({
        type: 'formScheme/getFormScheme',
        data: {
          id: selectedSchemes[0].formId,
        },
      });
    });
  }

  async allotSubmit(value: boolean, data: any) {
    let state: boolean = false;
    if (this.formScheme.formType === 0) {
      await (this.$refs.form0 as any).validator().then(async valid => {
        if (valid) {
          await (this.$refs.form0 as any).getData().then(data => {
            this.instance.formData = JSON.stringify(data);
            state = true;
          }).catch(error => {
          });
        }
      });
    }
    if (this.formScheme.formType === 1) {
      ((this.$refs.form1 as any).$refs.form as any).validate(valid => {
        if (valid) {
          this.instance.formData = JSON.stringify((this.$refs.form1 as any).getData());
          state = true;
        }
      });
    }
    if (state) {
      if (value && !data) {
        this.$Message.success({
          background: true,
          content: '流程 ' + this.instance.name + ' 已启动',
          duration: this.$config.duration,
        });
      } else {
        this.$Message.success({
          background: true,
          content: '流程 ' + data.name + ' 已重启',
          duration: this.$config.duration,
        });
      }
      Util.closePage(this, 'flow-instance-insert');
      this.$router.push({name: 'launch'});
    }
  }

  prevStep() {
    this.current--;
  }

  nextStep(step: number) {
    if (step === 0) {
      (this.$refs.instanceForm as any).validate(async (valid: boolean) => {
        if (valid) {
          this.current++;
        }
      });
    }
  }

  async restart() {
    this.type = 'restart';
    let state: boolean = false;
    if (this.formScheme.formType === 0) {
      await (this.$refs.form0 as any).validator().then(async valid => {
        if (valid) {
          await (this.$refs.form0 as any).getData().then(data => {
            this.instance.formData = JSON.stringify(data);
            state = true;
          }).catch(error => {
          });
        }
      });
    }
    if (this.formScheme.formType === 1) {
      ((this.$refs.form1 as any).$refs.form as any).validate(valid => {
        if (valid) {
          this.instance.formData = JSON.stringify((this.$refs.form1 as any).getData());
          state = true;
        }
      });
    }
    if (state) {
      if (this.$route.params.which == '4') {
        await this.$store.dispatch({
          type: 'flowInstance/restartFlowInstance',
          data: {
            flowInstance: this.instance,
          }
        });
        this.$Message.success({
          background: true,
          content: '流程 ' + this.instance.name + ' 已重启',
          duration: this.$config.duration,
        });
        Util.closePage(this, 'flow-instance-insert');
        this.$router.push({name: 'launch'});
      }
      if (this.$route.params.which == '5') {
        const runtime: Runtime = new Runtime(this.instance);
        if (runtime.nextNode.type === 'task' && (runtime.nextNode.info.allot === 'RUNNINGUSER' || runtime.nextNode.info.allot === 'RUNNINGROLE')) {
          this.allotModalData = {
            instance: this.instance,
            info: runtime.nextNode.info,
            creator: this.instance.creatorUserId
          };
          this.allotModalMount = true;
          this.$nextTick(() => {
            this.allotModalShow = true;
          });
        } else {
          await this.$store.dispatch({
            type: 'flowInstance/restartFlowInstance',
            data: {
              flowInstance: this.instance,
            }
          });
          this.$Message.success({
            background: true,
            content: '流程 ' + this.instance.name + ' 已重启',
            duration: this.$config.duration,
          });
          Util.closePage(this, 'flow-instance-insert');
          this.$router.push({name: 'launch'});
        }
      }
    }
  }


  @Watch('$store.state.flowInstance.instanceForEdit')
  change() {
    if (this.$route.params.id != '0') {
      this.instance = this.$store.state.flowInstance.instanceForEdit;
      this.selectedSchemes = [{
        id: this.instance.flowSchemeId,
        flowSchemeName: this.instance.flowSchemeName,
        flowSchemeContent: this.instance.flowSchemeContent,
      }];
      this.data = JSON.parse(this.instance.formData);
    }
  }


  mounted() {
  }

  async created() {
    if (this.$route.params.id != '0') {
      await this.$store.dispatch({
        type: 'flowInstance/getFlowInstanceForEdit',
        data: {
          id: this.$route.params.id,
        },
      });
      this.formScheme.formType = this.$store.state.flowInstance.instanceForEdit.formType;
      this.formScheme.schemeContent = this.$store.state.flowInstance.instanceForEdit.formSchemeContent;
      this.data = JSON.parse(this.$store.state.flowInstance.instanceForEdit.formData);
    }
  }
}
</script>

<style lang="less" scoped>
</style>
